<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.search"
        placeholder="模糊搜索"
        style="width: 200px;"
        size="small"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      ><i slot="prefix" class="el-input__icon el-icon-search" /></el-input>
      <el-button
        v-if="checkPermission(['admin','menu_create','menu_all'])"
        class="filter-item"
        size="small"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >新增</el-button>
    </div>
    <!--表格渲染-->
    <el-table v-if="checkPermission(['admin','menu_list','menu_all'])" v-loading="listLoading" :data="list" border size="small" row-key="id" default-expand-all>
      <el-table-column prop="name" label="图标" align="center" width="150%">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="icon" label="图标" align="center" width="80px">
        <template slot-scope="scope">
          <svg-icon v-if="scope.row.icon" :icon-class="scope.row.icon" />
        </template>
      </el-table-column>
      <el-table-column prop="sort" align="center" width="100px" label="排序">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.sort }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="path" label="链接地址" />
      <el-table-column :show-overflow-tooltip="true" prop="component" label="组件路径" />
      <el-table-column prop="is_frame" width="80px" label="内部菜单">
        <template slot-scope="scope">
          <span v-if="!scope.row.is_frame">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="is_frame" width="80px" label="是否显示">
        <template slot-scope="scope">
          <span v-if="scope.row.is_show">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150px" align="center">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(['admin','menu_edit','menu_all'])" type="primary" size="mini" :disabled="scope.row.id === 1" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <el-button v-if="checkPermission(['admin','menu_delete','menu_all'])" slot="reference" :disabled="scope.row.id === 1" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="600px">
      <el-form ref="dataForm" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="是否显示" prop="is_show">
          <el-radio-group v-model="form.is_show">
            <el-radio-button label="true">是</el-radio-button>
            <el-radio-button label="false">否</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <el-popover
            placement="bottom-start"
            width="460"
            trigger="click"
            @show="$refs['iconSelect'].reset()"
          >
            <IconSelect ref="iconSelect" @selected="selected" />
            <el-input slot="reference" v-model="form.icon" style="width: 460px;" placeholder="点击选择图标" readonly>
              <svg-icon v-if="form.icon" slot="prefix" :icon-class="form.icon" class="el-input__icon" style="height: 32px;width: 16px;" />
              <i v-else slot="prefix" class="el-icon-search el-input__icon" />
            </el-input>
          </el-popover>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="form.name" placeholder="名称" style="width: 460px;" />
        </el-form-item>
        <el-form-item label="菜单排序" prop="sort">
          <el-input v-model.number="form.sort" placeholder="序号越小越靠前" style="width: 460px;" />
        </el-form-item>
        <el-form-item label="内部菜单" prop="is_frame">
          <el-radio-group v-model="form.is_frame">
            <el-radio-button label="false">是</el-radio-button>
            <el-radio-button label="true">否</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="链接地址" prop="path">
          <el-input v-model="form.path" placeholder="菜单路径" style="width: 460px;" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="form.component" placeholder="组件路径" style="width: 460px;" />
        </el-form-item>
        <el-form-item label="父级菜单">
          <treeselect v-model="form.pid" :options="menus" placeholder="选择父级菜单" style="width:200px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import checkPermission from '@/utils/permission'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import IconSelect from '@/components/IconSelect'
import { getMenuTree, getMenus, delMenu, addMenu, editMenu } from '@/api/menu'
export default {
  components: { Pagination, IconSelect, Treeselect },
  data() {
    return {
      list: null,
      total: 0,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      listLoading: true,
      form: {
        id: '',
        name: '',
        sort: 999,
        path: '',
        component: '',
        is_show: 'true',
        is_frame: 'false',
        pid: null,
        icon: ''
      },
      rules: {
        is_show: [
          { required: true, message: '是否在导航栏显示', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入序号', trigger: 'blur', type: 'number' }
        ],
        is_frame: [
          { required: true, message: '请选择菜单类型', trigger: 'blur' }
        ],
        path: [
          { required: true, message: '请输入链接地址，注意不要和现有的地址重复', trigger: 'blur' }
        ],
        component: [
          { required: true, message: '请输入组件路径', trigger: 'blur' }
        ]

      },
      listQuery: {
        page: 1,
        limit: 10,
        search: undefined
      },
      columns: [
        {
          text: '名称',
          value: 'name'
        }
      ],
      menus: []
    }
  },
  created() {
    this.$nextTick(() => {
      this.getMenus()
      this.getList()
    })
  },
  methods: {
    checkPermission,
    getList() {
      getMenus(this.listQuery).then(response => {
        this.list = response.results
        this.total = response.count
        this.listLoading = false
        // Just to simulate the time of the request
        // setTimeout(() => {
        //   this.listLoading = false
        // }, 170)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    getMenus() {
      getMenuTree().then(res => {
        this.menus = res.data
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除此行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delMenu(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
          this.handleFilter()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    resetForm() {
      this.form = {
        name: '',
        sort: 999,
        is_show: true,
        is_frame: true,
        path: '',
        component: '',
        pid: null,
        icon: ''
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        // 清除
        this.$refs['dataForm'].resetFields()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addMenu(this.form).then(() => {
            this.resetForm()
            // this.list.unshift(this.temp)
            this.$message({
              type: 'success',
              message: '创建成功!,请手动刷新页面'
            })
            this.dialogFormVisible = false
            this.handleFilter()
          })
        }
      })
    },
    handleUpdate(row) {
      this.resetForm()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        // this.$refs['dataForm'].resetFields()
        this.$refs['dataForm'].clearValidate()
        this.form = { ...row }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editMenu(this.form.id, this.form).then(() => {
            for (const v of this.list) {
              if (v.id === this.form.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.form)
                break
              }
            }
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: '编辑成功!请手动刷新页面'
            })
            this.handleFilter()
          })
        }
      })
    },
    selected(name) {
      this.form.icon = name
    }
  }
}
</script>
